package com

import (
	"net"
	"alex/msc/helper"
	"fmt"
	"alex/ptp1588boundaryclock/com/general"
)

func MessageListener (port string, multicast bool, ip string, announceMsgChannel chan general.AnnounceMessage) {
	var connection *net.UDPConn
	if multicast {
		address := ip + ":" + port
		udpAddress, err := net.ResolveUDPAddr("udp4", address)
		helper.ErrHandling(err)
		connection, err = net.ListenMulticastUDP("udp", nil, udpAddress)
		helper.ErrHandling(err)
	} else {
		address := ":" + port
		udpAddress, err := net.ResolveUDPAddr("udp4", address)
		helper.ErrHandling(err)
		connection, err = net.ListenUDP("udp", udpAddress)
		helper.ErrHandling(err)
	}

	for {
		// infinite loop -> go routine
		handleClient(connection, announceMsgChannel)
	}
}

func handleClient (connection *net.UDPConn, announceMsgChannel chan general.AnnounceMessage) {
	var buffer [128] byte
	n, _, err := connection.ReadFromUDP(buffer[0:])
	helper.ErrHandling(err)
	if err == nil {
		checkBytes(buffer[:n], announceMsgChannel)
	}
}


// Checks the bytes of the received messages -> passes it on and
// sends the message on the appropriate channel.
func checkBytes (msg []byte, announceMsgChannel chan general.AnnounceMessage) {
	if len(msg) > 43 && len(msg) < 65 {
		header := new(Header)
		header.Init()
		if header.Read(msg[0:34], uint16(len(msg))) {
			fmt.Println("Header Read true!")
			// TODO: Sync, Follow_up, etc
			var msgTxt Message
			if header.MsgType == Announce {
				msgTxt = &general.AnnounceMessage{}
			}
			msgTxt.Init()
			if msgTxt.Read(msg[34:], uint16(0)) {
				fmt.Println("Message Read true")
				announceMsgChannel <- *msgTxt.(*general.AnnounceMessage)
				fmt.Println("Error at converting type...")
			} else {
				fmt.Println("Message Read error")
			}
		}
	}
}
